var servicesModule = angular.module('app.services');

/**
 * @ngInject
 */
var httpRequestInterceptor = function ($q, $injector, $filter) {

    // workaround to fix circular dependency, may be fixed in newer versions of angular
    function getToast() {
        return $injector.get('toastr');
    }

    function concatTextWithDelim(text1, text2, delim) {
        return text1 + delim + text2;
    }

    function getErrorReasonText(rejection, customReasonText) {
        var errorReasonText = !!rejection.data.Message
            ? rejection.data.Message
            : customReasonText;
        return concatTextWithDelim(rejection.statusText, errorReasonText, '. ');
    }

    return {

        request: function (config) {
            // Contains the data about the request before it is sent.
            // ... request checking logic
            return config || $q.when(config);
        },

        requestError: function (rejection) {
            getToast().error(getErrorReasonText(rejection, $filter('translate')('requestFailed')), concatTextWithDelim($filter('translate')('error'), rejection.status, ' '), { closeButton: true });

            return $q.reject(rejection);
        },

        response: function(response){

            switch(response.status) {
                case 401:
                    getToast().error(getErrorReasonText(response, $filter('translate')('responseFailed')), concatTextWithDelim($filter('translate')('error'), response.status, ' '), { closeButton: true });
                    break;
            }

            return response || $q.when(response);
        },

        responseError: function (rejection) {

            switch(rejection.status) {
                case 401:
                    getToast().error(getErrorReasonText(rejection, $filter('translate')('responseFailed')), concatTextWithDelim($filter('translate')('error'), rejection.status, ' '), { closeButton: true });
                    break;
                default:
                    getToast().error(getErrorReasonText(rejection, $filter('translate')('responseFailed')), concatTextWithDelim($filter('translate')('error'), rejection.status, ' '), { closeButton: true });
            }

            return $q.reject(rejection);
        }
    };
};

servicesModule.factory('httpRequestInterceptor', httpRequestInterceptor);
